import { Ref, SetupContext, computed, ref, watch } from "vue";
import { ListViewProps, MultiSelectMode } from "../list-view.props";
import { UseDataView, UseSelection } from "./types";

export function useSelection(
    props: ListViewProps,
    context: SetupContext,
    useDataViewCompostion: UseDataView
): UseSelection {
    const identifyField = ref(props.idField);
    const enableMultiSelect = ref(props.multiSelect);
    const multiSelectMode: Ref<MultiSelectMode> = ref(props.multiSelectMode as MultiSelectMode);
    const { getSelectionItems } = useDataViewCompostion;

    const selectedItems: Ref<any[]> = ref(getSelectionItems(props.selectionValues));

    watch(() => props.selectionValues, (newValues: any[]) => {
        selectedItems.value = ref(getSelectionItems(newValues)).value;
    });

    const shouldClearSelection = computed(() => {
        return !enableMultiSelect.value;
    });

    function getKey(item: any) {
        return item[identifyField.value] || '';
    }

    function findIndexInSelectedItems(item: any): number {
        const selectItemIndex = selectedItems.value.findIndex((selectedItem: any) => {
            return getKey(selectedItem) === getKey(item);
        });
        return selectItemIndex;
    }

    function clearSelection() {
        selectedItems.value.forEach((selectionItem: any) => { selectionItem.checked = false; });
        selectedItems.value = [];
    }

    function toggleSelectItem(item: any, index: number) {
        if (shouldClearSelection.value) {
            clearSelection();
        }

        const currentItemIndexInSelection = findIndexInSelectedItems(item);
        const hasSelectedCurrentItem = currentItemIndexInSelection > -1;

        if (hasSelectedCurrentItem) {
            selectedItems.value.splice(currentItemIndexInSelection, 1);
            item.checked = false;
        } else {
            selectedItems.value.push(item);
            item.checked = true;
        }
        context.emit('selectionChange', selectedItems.value);
    }

    return { clearSelection, findIndexInSelectedItems, selectedItems, toggleSelectItem };
}
